import os, logging, logging.handlers
from signal import SIGKILL

def AddSep(s):
	if not s.endswith(os.sep):
		s = s + os.sep
	return s

def WritePID(pid, pid_dir, pid_file="cognition.pid", LOG=False):
	if LOG:
		LOG.info("\tWriting Process ID to file: %s" % (AddSep(os.getcwd()) + AddSep(pid_dir) + pid_file))
	try:
		f = open(AddSep(os.getcwd()) + AddSep(pid_dir) + pid_file, "w")
		f.write(str(pid))
		f.close()
		if LOG:
			LOG.info("\tCreated Process ID (%s)" % str(pid))
		return True
	except OSError, e:
		if LOG:
			LOG.error("\tError creating Process ID: %s" % (e.strerror))
		return False
	except IOError, e:
		if LOG:
			LOG.error("\tError creating Process ID: %s" % (e.strerror))
		return False

def GetPID(pid_dir, pid_file, LOG=False):
	try:
		if LOG:
			LOG.info("\tAcquiring Process ID from %s" % pid_dir)
		
		f = open(AddSep(os.getcwd()) + AddSep(pid_dir) + pid_file, "r").read()
		if LOG:
			LOG.info("\tProcess ID Acquired: %s" % str(f))
		return f
	except OSError, e:
		if LOG:
			LOG.error("\tCould not acquire Process ID (%s)" % e.strerror)
		return 0
	except IOError, e:
		if LOG:
			LOG.error("\tCould not acquire Process ID (%s)" % e.strerror)
		return 0

def ClearPID(pid_dir, pid_file, LOG=False):
	if LOG:
		LOG.info("\tClearing Process ID from %s" % pid_dir)
	try:
		os.remove(AddSep(os.getcwd()) + AddSep(pid_dir) + pid_file)
		if LOG:
			LOG.info("\tProcess ID cleared (%s)" % (AddSep(os.getcwd()) + AddSep(pid_dir) + pid_file))
		return True
	except OSError, e:
		if LOG:
			LOG.error("\tFailed to clear Process ID (%s)" % e.strerror)
		return False
	except IOError, e:
		if LOG:
			LOG.error("\tFailed to clear Process ID (%s)" % e.strerror)
		return False

def Log(conf):
	if "dir" in conf:
		LOG_DIR = conf["dir"]
	else:
		LOG_DIR = "logs"
	
	if "cognition" in conf:
		LOG_FILE = AddSep(LOG_DIR) + conf["cognition"]
	else:
		LOG_FILE = AddSep(LOG_DIR) + "cognition.log"
	
	if not os.path.exists(LOG_DIR):
		os.mkdir(LOG_DIR)
	else:
		if not os.path.isdir(LOG_DIR):
			os.mkdir(LOG_DIR)
	
	if not os.path.exists(LOG_FILE):
		f = open(LOG_FILE, "wb")
		f.write("Cognition Logger...\n")
		f.close()
	
	FORMAT = "%(levelname)s :: %(message)s"
	logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG, format=FORMAT)
	return logging

def CreateDaemon(LOG=False, WORKDIR=False, log_prefix="DAEMONIZER"):
	UMASK = 027
	if not WORKDIR:
		WORKDIR = os.getcwd()
	if LOG:
		LOG.info(log_prefix + ": Creating daemon process:\n\t\tWORKDIR: %s\n\t\tUMASK: %s" % (WORKDIR, UMASK))
	
	try:
		pid = os.fork()
		if LOG:
			LOG.info(log_prefix + ": Process forked.")
	except OSError, e:
		if LOG:
			LOG.error(log_prefix + ": OSError, %s" % e.strerror)
		raise Execption, "%s: %d" % (e.strerror, e.errno)
	if pid == 0:
		os.setsid()
		try:
			pid = os.fork()
			if LOG:
				LOG.info(log_prefix + ": Process double-forked.")
		except OSError, e:
			if LOG:
				LOG.error(log_prefix + ": OSError, %s" % e.strerror)
			raise Exception, "%s: %d" % (e.strerror, e.errno)
		if pid == 0:
			os.chdir(WORKDIR)
			os.umask(UMASK)
		else:
			os._exit(0)
	else:
		os.wait()
		os._exit(0)
	
	if LOG:
		# LOG.info("DAEMONIZER: Resource limits set.")
		LOG.info(log_prefix + ": Daemon created.")
	
	return 0
